<template>
  <cus-form :nodes="nodes" ref="formRef"></cus-form>
</template>
<script lang="ts">
import { ref, Ref } from 'vue'
import { ElMessage } from 'element-plus';
import $, { emitter } from '$';
export default {
  props: {
    selectData: {
      type: Array,
      default: () => ([])
    }
  },
  setup(props) {
    let formRef = ref();
    let subjectId = ref();
    emitter.emit('effect', async (e) => {
      subjectId.value = e
      $.http.post('/admin/knowledgeTemplate/query', { subjectId: e }).then((res) => {
        if(res.result) {
          res.json.map((v: any) => {
            v.name = v.title
          })
          nodes.value[2].options = res.json;
        }
      })
    });
    setTimeout(() => {
      nodes.value[0].options = props.selectData;
    })
    // let defaltData: any = props.selectData[0] //单选
    let defaltData: any[] = props.selectData.map((item: any) => { return item.id }) //多选
    let nodes: Ref<any> = ref([
      // { label: '知识元', type: 'select', key: 'knowledgeId', options: [ ], filterable: true, default: defaltData.id},
      { label: '知识元', type: 'select', key: 'knowledgeIds', options: [ ], filterable: true, default: defaltData, multiple: true},
      { label: '名称', type: 'input', key: 'title', rule: { required: true, message: '请输入名称' }},
      { label: '模板', type: 'select', key: 'templateId', options: [ ], rule: { required: true, message: '请选择模板' } },
    ]);

    const save = (resolve, reject) => {
       formRef.value.validate(valid => {
         if(valid) {
           let data = {
             ...valid,
             subjectId: subjectId.value,
           }
          $.http.json('/admin/knowledgeManager/save', data).then((res) => {
            if(res.result) {
              resolve();
              ElMessage.success('新建知识元成功~！');
              emitter.emit('knowledge-init');
            }else {
              reject()
            }
          })
         }
       })
    }
    return { nodes, save, formRef }
  }
}
</script>

<style lang="scss" scoped>

</style>